import Vue from 'vue'
import store from '../store'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { staticRoutes } from '@/router/routes'
import {  clearSession, getLocal} from '@/utils/storage'
import { genRoutesAndMenus } from '@/utils/routeMenu'

// 解决 `element ui` 导航栏重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

// 加载静态路由
const createRouter = () => new VueRouter({
  scrollBehavior: () => ({ y: 0 }),
  routes: staticRoutes
})
const router = createRouter()


NProgress.configure({ showSpinner: false })

// 路由加载前
router.beforeEach((to, from, next) => {
  //console.log("准备跳转路由"+to.fullPath)
  document.title = to.name || 'vue-admin-wonderful'
  NProgress.start()
  keepAliveSplice(to)
  let token = getLocal('token')
  console.log("访问路由",to.fullPath)
  if (to.fullPath === '/login') {
    next()
    //NProgress.done()
  } else {
    if (!token) {
      console.log("token不存在，跳转 login")
      next('/login')
      clearSession()
      store.dispatch('clearUserInfo').then();
      //  NProgress.done()
    } else {
      //console.log("token存在"+token)
      // 动态加载后端返回路由路由(模拟数据)
      //if (!store.state.userInfo) {
      if (!store.state.userInfo || Object.keys(store.state.userInfo)<=0) {
        console.log("userInfo不存在，重新查询用户信息")
        //查询用户信息
        store.dispatch("genUserInfo").then(() => {
          //console.log("dispatch genUserInfo 结束，返回 router",data)
          addDynamic(router,to,next)
        })
      } else if (Object.keys(store.state.menus).length <= 0) {
        console.log("菜单没有，重新获取一次菜单")
        addDynamic(router,to,next)
        /*genRoutesAndMenus(router, to, next).then(()=>{
          next({ ...to, replace: true })
        })*/
      } else {
        console.log("执行正常程序")
        next()
      }
    }
  }
})

function addDynamic(router,to,next){
  genRoutesAndMenus().then((rootRouter) =>{
    resetRouter()
    console.log("rootRouter ",rootRouter)
    router.addRoute(rootRouter)
    router.options.routes.push(rootRouter) ;
    //没有匹配的全部都为404
    //let r404={ path: '*', redirect: '/404',meta:{} }
    //router.addRoute(r404)
    //router.options.routes.push(r404);
    next({ ...to, replace: true })
  })
}

// 路由加载后
router.afterEach(() => {
  NProgress.done()
})

// 递归处理多余的 layout : <router-view>，让需要访问的组件保持在第一层 layout 层。
// 因为 `keep-alive` 只能缓存二级路由
// 默认初始化时就执行
export function keepAliveSplice(to) {
  if (to.matched && to.matched.length > 2) {
    to.matched.map((v, k) => {
      if (v.components.default instanceof Function) {
        v.components.default().then(components => {
          if (components.default.name === 'publics') {
            to.matched.splice(k, 1)
            router.push({ path: to.path, query: to.query })
            keepAliveSplice(to)
          }
        })
      } else {
        if (v.components.default.name === 'publics') {
          to.matched.splice(k, 1)
          keepAliveSplice(to)
        }
      }
    })
  }
}

// 重置路由
export function resetRouter() {
  router.matcher = createRouter().matcher
}

// 导出路由
export default router
